package com.nbcio.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbcio.common.core.exception.ServiceException;
import com.nbcio.common.core.utils.MapstructUtils;


import com.nbcio.common.core.utils.StringUtils;
import com.nbcio.common.mybatis.core.page.PageQuery;
import com.nbcio.common.mybatis.core.page.TableDataInfo;
import com.nbcio.iot.domain.entity.IotProduct;
import com.nbcio.iot.domain.bo.IotProductBo;
import com.nbcio.iot.domain.vo.IotProductVo;
import com.nbcio.iot.mapper.IotProductMapper;
import com.nbcio.iot.service.IIotProductService;

import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 物联网产品服务实现
 */
@Service
@RequiredArgsConstructor
public class IotProductServiceImpl implements IIotProductService {

    private final IotProductMapper baseMapper;

    @Override
    public TableDataInfo<IotProductVo> queryPageList(IotProductBo bo, PageQuery pageQuery) {
        IotProduct build = MapstructUtils.convert(bo, IotProduct.class);
        if (build == null) {
            build = new IotProduct();
        }
        
        // 使用自定义的查询方法，包含分类名称
        List<IotProductVo> list = baseMapper.selectProductList(build);
        
        // 手动分页
        int start = (int) ((pageQuery.getPageNum() - 1) * pageQuery.getPageSize());
        int end = Math.min(start + (int) pageQuery.getPageSize(), list.size());
        List<IotProductVo> pageList = list.subList(start, end);
        
        return new TableDataInfo<>(pageList, (long) list.size());
    }

    @Override
    public List<IotProductVo> queryList(IotProductBo bo) {
        IotProduct build = MapstructUtils.convert(bo, IotProduct.class);
        if (build == null) {
            build = new IotProduct();
        }
        
        // 使用自定义的查询方法，包含分类名称
        return baseMapper.selectProductList(build);
    }

    @Override
    public IotProductVo queryById(Long productId) {
        // 使用自定义查询，确保包含分类名称与 flow_id 等字段
        return baseMapper.selectProductById(productId);
    }

    @Override
    public Boolean insertByBo(IotProductBo bo) {
        IotProduct add = MapstructUtils.convert(bo, IotProduct.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setProductId(add.getProductId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(IotProductBo bo) {
        IotProduct update = MapstructUtils.convert(bo, IotProduct.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public long countByCategoryId(Long categoryId) {
        LambdaQueryWrapper<IotProduct> lqw = Wrappers.lambdaQuery();
        lqw.eq(IotProduct::getCategoryId, categoryId);
        return baseMapper.selectCount(lqw);
    }

    @Override
    public Boolean checkProductNameUnique(IotProductBo bo) {
        LambdaQueryWrapper<IotProduct> lqw = Wrappers.lambdaQuery();
        lqw.eq(IotProduct::getProductName, bo.getProductName())
            .ne(ObjectUtil.isNotNull(bo.getProductId()), IotProduct::getProductId, bo.getProductId());
        return baseMapper.selectCount(lqw) == 0;
    }

    @Override
    public Boolean checkProductCodeUnique(IotProductBo bo) {
        LambdaQueryWrapper<IotProduct> lqw = Wrappers.lambdaQuery();
        lqw.eq(IotProduct::getProductCode, bo.getProductCode())
            .ne(ObjectUtil.isNotNull(bo.getProductId()), IotProduct::getProductId, bo.getProductId());
        return baseMapper.selectCount(lqw) == 0;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<IotProduct> buildQueryWrapper(IotProductBo bo) {
        LambdaQueryWrapper<IotProduct> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getProductName()), IotProduct::getProductName, bo.getProductName())
            .eq(StringUtils.isNotBlank(bo.getProductCode()), IotProduct::getProductCode, bo.getProductCode())
            .eq(ObjectUtil.isNotNull(bo.getCategoryId()), IotProduct::getCategoryId, bo.getCategoryId())
            .eq(StringUtils.isNotBlank(bo.getDeviceType()), IotProduct::getDeviceType, bo.getDeviceType())
            .eq(StringUtils.isNotBlank(bo.getBrand()), IotProduct::getBrand, bo.getBrand())
            .eq(StringUtils.isNotBlank(bo.getProtocolType()), IotProduct::getProtocolType, bo.getProtocolType())
            .eq(StringUtils.isNotBlank(bo.getSupplier()), IotProduct::getSupplier, bo.getSupplier())
            .eq(StringUtils.isNotBlank(bo.getStatus()), IotProduct::getStatus, bo.getStatus())
            .orderByDesc(IotProduct::getCreateTime);
        return lqw;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IotProduct entity) {
        // 校验产品名称唯一性
        if (!checkProductNameUnique(MapstructUtils.convert(entity, IotProductBo.class))) {
            throw new ServiceException("新增产品'" + entity.getProductName() + "'失败，产品名称已存在");
        }
        // 校验产品编码唯一性
        if (!checkProductCodeUnique(MapstructUtils.convert(entity, IotProductBo.class))) {
            throw new ServiceException("新增产品'" + entity.getProductName() + "'失败，产品编码已存在");
        }
    }
} 